﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace TM.Unofficial.Chat
{
	/// <summary>
	/// One chat stream
	/// </summary>
	public class ChatWindow
	{
		public TMObjects.Member ChatPartner { get; private set; }

		Unofficial.Network.VBrowser browser;
		private int lastupdate_id = 0;

		/// <summary>
		/// creates a new chat window
		/// </summary>
		/// <param name="browser"></param>
		/// <param name="userid"></param>
		public ChatWindow(Unofficial.Network.VBrowser browser, TMObjects.Member chatpartner)
		{
			//init vars
			this.browser = browser;
			this.ChatPartner = chatpartner;
		}

		/// <summary>
		/// Write a message
		/// </summary>
		/// <param name="message">message to write</param>
		public string WriteMessage(string message)
		{
			//Try to write a message
			string xmlresult = browser.PostRequest(new Uri("http://thats-me.ch/tm-im-new/ajax_sendmsg.php"), Encoding.UTF8.GetBytes("msg=" + message + "&to=" + this.ChatPartner.ID.ToString()), false);

			//lastmessage int noch updaten sowie parsing und ausgeben der messages
			XmlDocument xmldoc = new XmlDocument();
			xmldoc.LoadXml(xmlresult);
			
			this.lastupdate_id = Convert.ToInt32(xmldoc.GetElementsByTagName("lastid")[0].InnerText);
			return xmldoc.GetElementsByTagName("txt")[0].InnerText;
		}

		/// <summary>
		/// reads messages since last view
		/// </summary>
		public string ReadLastMessage()
		{
			
			string returnval = "";
			//Try to read last message
			string xmlresult = browser.GetRequest(new Uri("http://thats-me.ch/tm-im-new/ajax_update.php"), false);

			//parse result
			XmlDocument xmldoc = new XmlDocument();
			xmldoc.LoadXml(xmlresult);

			//this.lastupdate_id = Convert.ToInt32(xmldoc.GetElementsByTagName("lastid")[0].InnerText);
			XmlNodeList chats = xmldoc.GetElementsByTagName("chats");
			
			foreach(XmlNode node in chats)
			{
				if(node.SelectSingleNode("to").InnerText == this.ChatPartner.ID.ToString())
				{
					returnval = node.SelectSingleNode("txt").InnerText;
					
					if (node.SelectSingleNode("lastid").InnerText != string.Empty)
					{
						this.lastupdate_id = Convert.ToInt32(node.SelectSingleNode("lastid").InnerText);
					}
				}
			}
			
			return returnval;
		}
	}
}
